<?php

class DataController extends Controller
{

	/**
	 * 数据导入
	 */
	public function actionImport($type = null)
	{
		switch ($type) {
			case 'db' :
				$this->actionImportDb();
				break;
			case 'csv':
			default:
				$this->actionImportCsv();
				break;
		}
	}

	/**
	 * CSV 文件导入
	 */
	protected function actionImportCsv()
	{
		$model = new ImportCsvForm();
		if (Yii::app()->request->isPostRequest) {
			$model->attributes = $_POST['ImportCsvForm'];
			if ($model->validate()) {
				try {
					$file = CUploadedFile::getInstance($model, 'file');
					if (($fd = @fopen($file->tempName, 'r')) === false) {
						throw new XSException('无法读取上传的临时文件');
					}
					$fields = null;
					$numErr = $numOk = 0;
					$docModel = new DocModel($this->projectName);
					$index = $docModel->getXS()->index; /* @var $index XSIndex */
					$index->openBuffer();
					while (($row = fgetcsv($fd, 0, $model->realDelim)) !== false) {
						// init fields
						if (is_null($fields)) {
							$fields = array_keys($docModel->getXS()->getAllFields());
							// check first line
							$isHead = true;
							foreach ($row as $tmp) {
								if (!in_array($tmp, $fields)) {
									$isHead = false;
									break;
								}
							}
							if ($isHead) {
								$fields = $row;
								continue;
							}
						}
						// parse as fields
						$data = array();
						for ($i = 0; $i < count($fields); $i++) {
							if (!isset($row[$i])) {
								break;
							}
							$data[$fields[$i]] = $row[$i];
						}
						try {
							$doc = new XSDocument();
							$doc->setFields($data);
							$index->update($doc);
							$numOk++;
						} catch (XSException $e) {
							$numErr++;
						}
					}
					fclose($fd);
					$index->closeBuffer();
					$index->flushIndex();
					$docModel->cleanRemovedCache();
					Yii::app()->user->setFlash('success', '成功导入数据 ' . $numOk . ' 条，' . '失败 ' . $numErr . ' 条');
				} catch (XSException $e) {
					Yii::app()->user->setFlash('error', '导入失败：' . $e->getMessage());
				}
			}
		} else {
			Yii::app()->user->setFlash('info', '导入数据必须是 UTF-8 编码，而且只是追加记录并不会清空已有索引数据。');
		}
		$this->render('import_csv', array('model' => $model));
	}

	/**
	 * 数据库导入 (via Ajax)
	 */
	protected function actionImportDb()
	{
		$model = new ImportDbForm();
		if (Yii::app()->request->isAjaxRequest && Yii::app()->request->isPostRequest) {
			$model->attributes = $_POST['ImportDbForm'];
			if ($model->offset < 0) {
				echo CActiveForm::validate($model);
			} else {
				$result = array('ok' => 1);
				if (!$model->validate()) {
					$result['ok'] = 0;
					$result['msg'] = '';
					foreach ($model->getErrors() as $errors) {
						$result['msg'] .= implode("\n", $errors) . "\n";
					}
				} else {
					$result['fail'] = $result['count'] = 0;
					$result['offset'] = -1;
					try {
						$docModel = new DocModel($this->projectName);
						$index = $docModel->getXS()->index; /* @var $index XSIndex */
						$index->openBuffer();
						while ($row = $model->getData()) {
							try {
								$doc = new XSDocument();
								$doc->setFields($row);
								$index->update($doc);
								$result['count']++;
							} catch (XSException $e) {
								$result['fail']++;
							}
						}
						$index->closeBuffer();
						$index->flushIndex();
						if (($result['count'] + $result['fail']) >= ImportDbForm::LIMIT) {
							$result['offset'] = $model->offset + ImportDbForm::LIMIT;
						}
						$docModel->cleanRemovedCache();
					} catch (XSException $e) {
						$result['ok'] = 0;
						$result['msg'] = '出错：' . $e->getMessage();
					}
				}
				echo CJSON::encode($result);
			}
			Yii::app()->end();
		}
		$this->render('import_db', array('model' => $model));
	}

	/**
	 * 添加数据
	 */
	public function actionCreate()
	{
		$this->actionUpdate(null);
	}

	/**
	 * 更新数据
	 */
	public function actionUpdate($id)
	{
		$model = new DocModel($this->projectName);
		if (Yii::app()->request->isPostRequest) {
			$model->attributes = $_POST['DocModel'];
			if ($model->save()) {
				$this->redirect(array('data/list'));
			} elseif (!$model->hasErrors()) {
				$model->addError($model->getXS()->getFieldId()->name, '数据保存失败，请检查项目配置是否正确，服务端服务是否开启');
			}
		} elseif ($id !== null && $model->findByPk($id) === null) {
			throw new CHttpException(404, 'Data not found(#' . $id . ')');
		}
		$this->render('add', array('model' => $model));
	}

	/**
	 * 数据列表
	 */
	public function actionList()
	{
		$model = new DocModel($this->projectName);
		$q = Yii::app()->request->getParam('q', null);
		$dataProvider = new DocDataProvider($model, array(
			'query' => $q,
		));
		$gridColumns = array();
		$gridColumns[] = array(
			'class' => 'bootstrap.widgets.TbButtonColumn',
			'htmlOptions' => array('nowrap' => 'nowrap'),
			'template' => '{update} {delete}',
		);
		$fid = $model->getXS()->getFieldId()->name;
		$ftitle = $model->getXS()->getFieldTitle()->name;
		foreach ($model->attributeNames() as $name) {
			$column = array(
				'class' => 'GridDataColumn',
				'name' => $name,
				'maxLength' => 30,
				'header' => $model->getAttributeLabel($name),
			);
			if ($name === $fid || $name === $ftitle) {
				$column['url'] = 'array("data/update","id"=>$data["' . $fid . '"])';
			}
			$gridColumns[] = $column;
		}
		$this->render('list', array(
			'gridDataProvider' => $dataProvider,
			'gridColumns' => $gridColumns,
			'q' => $q,
			'model' => $model,
		));
	}

	/**
	 * 数据删除
	 */
	public function actionDelete($id)
	{
		$model = new DocModel($this->projectName);
		$model->deleteByPk($id);
	}

	/**
	 * 清空索引
	 */
	public function actionClean()
	{
		$user = Yii::app()->user; /* @var $user WebUser */
		$model = new CleanForm();
		if (Yii::app()->request->isPostRequest) {
			$model->attributes = $_POST['CleanForm'];
			if ($model->validate()) {
				try {
					$docModel = new DocModel($this->projectName);
					if ($model->stopRebuild) {
						$docModel->getXS()->index->stopRebuild();
					}
					$docModel->clean();
					$user->setFlash('success', '已清空该项目全部索引数据');
				} catch (XSException $e) {
					$user->setFlash('error', '清除索引失败：' . $e->getMessage());
				}
			}
		}
		if (!$user->hasFlash('error') && !$user->hasFlash('success')) {
			$user->setFlash('warning', '本操作将清空该项目下的所有索引数据、同义词库，请慎重');
		}
		$this->render('clean', array('model' => $model));
	}
}
